package com.dullfox.sbm.controller;

import com.dullfox.sbm.common.auth.AuthIgnore;
import com.dullfox.sbm.common.auth.AuthManager;
import com.dullfox.sbm.common.bean.Result;
import com.dullfox.sbm.common.global.RunException;
import com.dullfox.sbm.common.util.ConstUtil;
import com.dullfox.sbm.model.SysUser;
import com.dullfox.sbm.model.vo.SysUserVo;
import com.dullfox.sbm.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: zengdy
 * Date: 2018/10/25
 */
@Controller
@RequestMapping(value = "/loginController")
public class LoginController {

    @Autowired
    private AuthManager authManager;

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping(value = "/login")
    @AuthIgnore
    @ResponseBody
    public Result login(@RequestBody SysUser sysUser) {
        if (StringUtils.isBlank(sysUser.getName())) {
            throw new RunException(ConstUtil.ERROR_CODE, "name为空");
        }
        if (StringUtils.isBlank(sysUser.getPwd())) {
            throw new RunException(ConstUtil.ERROR_CODE, "pwd为空");
        }
        Result ret = new Result();
        SysUserVo vo = new SysUserVo();
        vo.setName(sysUser.getName());
        vo.setPwd(sysUser.getPwd());
        SysUser retUser = sysUserService.login(vo);
        if (null == retUser) {
            ret.setCode(ConstUtil.ERROR_CODE);
            ret.setMsg("用户名或密码错误");
        } else {
            String token = authManager.signIn(retUser);
            Map<String, Object> data = new HashMap<>();
            data.put("user", retUser);
            data.put("token", token);
            ret.setData(data);
        }
        return ret;
    }

}
